package com.atguigu.yygh.sms.service.impl;

import com.atguigu.yygh.common.utils.RandomUtil;
import com.atguigu.yygh.common.utils.SmsUtil;
import com.atguigu.yygh.sms.service.SmsService;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean send(String phone) throws TencentCloudSDKException {
        //判断redis中是否已有验证码
        Object codeDB = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(codeDB)) {
            return true;
        }

        String code = RandomUtil.getFourBitRandom(); //验证码
        int time = 5; //有效时间
        //发送短信
        boolean flag = SmsUtil.sendMsg(phone, code, time + "");
        if (flag) {
            //发送成功，则将验证码存入redis
            redisTemplate.opsForValue().set(phone, code, time, TimeUnit.MINUTES);
            return true;
        }
        return false;
    }
}